package bairui.international.console.web.controller.barter.property;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lianjing.sh.spring.web.controller.base.action.Action;
import com.lianjing.sh.spring.web.controller.enhance.output.FomatOutput;
import com.lianjing.sh.validate.spring.util.Util_Validate;
import com.sh_lianjing.file.excel.bean.RowInfo;
import com.sh_lianjing.file.excel.bean.SheetInfo;
import com.sh_lianjing.file.excel.read.ExcelReaderBeanSupport;
import com.sh_lianjing.file.excel.read.parsevisitor.ExcelParseVisitorSupport;

import bairui.international.model.domain.jpa.TB_ProductProperty;
import bairui.international.service.Service_ProductProperty;

/**
 *
 * 导入
 *
 * @generated
 * 
 * @see STest_C_Barter_Property_Import_ExcelImport 测试
 *
 */
@Controller
public class C_Barter_Property_Import_ExcelImport
 extends SC_Barter_Property_Import_ExcelImport 
{
	
	@Autowired private org.springframework.validation.Validator validator;
	@Autowired private Service_ProductProperty service_ProductProperty;
	
	/**
	 * 导入Excel数据
	 */
	@Action(ExcelImport.class)
	@PostMapping(value=ExcelImport.RequestMappingValue)
	public @FomatOutput @ResponseBody Object excelImport(
		@Valid ExcelInput_ExcelImport_Excel_Input input
	) throws Exception {
		// 解析excel
		List<TB_ProductProperty> beans = parseExcel(input.getExcelFile());
		// 保存数据
		service_ProductProperty.excelImportSaves(beans);
		return null;
	}
	
	/**
	 * 解析excel工具函数
	 * @param binder 
	 * @param result 
	 */
	private List<TB_ProductProperty> parseExcel(MultipartFile file) throws Exception{
		List<TB_ProductProperty> beans = new ArrayList<>();
		//
		try(ExcelReaderBeanSupport excelIO = new ExcelReaderBeanSupport(file.getInputStream())){
			excelIO.read(ExcelInput_ExcelImport_Excel_Input.Model.class, new ExcelParseVisitorSupport<ExcelInput_ExcelImport_Excel_Input.Model>() {
				@Override
				public void run(
					SheetInfo<Sheet> sheetInfo, 
					RowInfo<Row> rowInfo, 
					Map<String, List<String>> head,
					ExcelInput_ExcelImport_Excel_Input.Model parseModel
				) throws BindException {
					if(parseModel.getName() == null){
						return;
					}
					// 验证
					Util_Validate.validate(validator, parseModel);
					//
					beans.add(new TB_ProductProperty(parseModel));
				}
			});
		}
		return beans;
	}
	
	

}
